package com.lza.handle;

import com.lza.response.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileLoaderHandle {
    //设置日期格式
    SimpleDateFormat sdf=new SimpleDateFormat("yyy/MM/dd");
    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file, HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        if(!originalFilename.endsWith(".jpg")){
            return Result.error().getMessage("上传格式错误");
        }
        //文件目录
        String format=sdf.format(new Date());
        //request.getSession().getServletContext() 获取的是Servlet容器对象，相当于tomcat容器了。getRealPath("/") 获取实际路径，“/”指代项目根目录
        String realpath = request.getServletContext().getRealPath("/") + format;//临时路径
        File folder = new File(realpath);
        System.out.println(realpath);
        if(!folder.exists()){
            folder.mkdirs();//如果文件不存在，就创建出来
        }
        //创建新的文件名
        String newName = UUID.randomUUID().toString() + ".jpg";
        try {
            file.transferTo(new File(folder,newName));
            //http://localhost:8083/2021/08/31/fc5f59a6-a6d1-45ee-8b44-0aeeff334328.jpg项目重启就没有了
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/" + format +"/"+ newName;
            return Result.ok().getData("文件上传成功,url地址是",url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().getData("文件上传失败",e.getMessage());
        }
    }
}
